﻿@page "/AppFiles"

@using BootstrapBlazor.Components

<div class="row">
    <div class="col-12 col-m-5 col-x-4 col-xl-3">

        Files:

        <pre>
            @{
                var files1 = Directory.GetFiles(UploadPath);
                var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory.Replace("/files", ""), "*.*", SearchOption.AllDirectories);
                int i = 0;
                foreach (var item in files)
                {
                    i++;
                    <button class="btn btn-link" @onclick="(async()=>await PreviewFile(item))">@($"{i}.{item}")</button><br />
                }
            }
        </pre>


        <FileUpload ShowFileList="false" Lite FileChanged="_=>StateHasChanged()" />

        <div style="padding-top:30px">
            <a class="btn btn-primary" @onclick="_=>DownloadDemoFiles()">
                <span class="oi oi-file" aria-hidden="true"></span> 演示文件
            </a>
            <a class="btn btn-danger" @onclick="_=>EmptyFiles()">
                <span class="oi oi-delete" aria-hidden="true"></span> 清空文件
            </a>
        </div>

    </div>

    <div class="col-12 col-m-7 col-x-8 col-xl-9">

        @Status

        @if (stream != null)
        {
            <PdfReader Stream="stream" @key="stream" />
        }
        else if (FilePreview != null)
        {
            <FileViewer Filename="@FilePreview" @key="FilePreview" />
        }
        else if (ImagePreview != null)
        {
            <Viewer Src="@ImagePreview" Width="600px" Height="300px" LocalFileToStream @key="ImagePreview" />

            @*<img src="@ImagePreview">*@
        }
        else
        {
            @Message
        }
    </div>
</div>





@code{

    protected string UploadPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "uploads");

    Stream stream { get; set; }

    string FilePreview { get; set; }

    string ImagePreview { get; set; }

    string Message { get; set; }

    string Status { get; set; }

    async Task PreviewFile(string filename)
    {
        Reset();

        Status = "处理中";
        StateHasChanged();
        await Task.Delay(100);

        filename = Path.Combine(UploadPath, filename);

        if (File.Exists(filename))
        {
            var extension = Path.GetExtension(filename);
            if (extension == ".pdf")
            {
                stream = File.OpenRead(filename);
            }
            else if (extension == ".xlsx" || extension == ".docx")
            {
                FilePreview = filename;
            }
            else if (extension == ".png" || extension == ".jpg" || extension == ".jpeg" || extension == ".gif" || extension == ".bmp")
            {
                ImagePreview = filename;

                //不用组件就自己处理
                //ImagePreview = PopulateImageFromStream(File.OpenRead(filename));
            }
            else if (extension == ".txt" || extension == ".csv" || extension == ".xml" || extension == ".log" || extension == ".htm" || extension == ".html" || extension == ".css" || extension == ".js")
            {
                Message = File.ReadAllText(filename);
            }
            else
            {
                Message = $"目前还无法预览{extension}类型文件";
            }
        }
        else
        {
            stream = null;
            FilePreview = null;
        }

        Status = null;

    }

    private string PopulateImageFromStream(Stream stream)
    {
        MemoryStream ms = new MemoryStream();
        stream.CopyTo(ms);
        byte[] byteArray = ms.ToArray();
        var b64String = Convert.ToBase64String(byteArray);
        return "data:image/png;base64," + b64String;
    }

    void Reset()
    {
        stream = null;
        FilePreview = null;
        ImagePreview = null;
        Message = null;
        Status = null;
    }

    async Task DownloadDemoFiles()
    {
        Reset();

        Status = "下载演示文件中";
        StateHasChanged();

        string[] url1 = {
            "sample.jpg", "sample2.jpg", "sample3.jpg",
            "sample.png",
            "sample.xlsx", "sample2.xlsx", "sample3.xlsx",
            "sample.pdf", "sample2.pdf",
            "sample.docx", "sample2.docx"
        };

        using (HttpClient client = new HttpClient())
        {
            foreach (var item in url1.ToList())
            {
                System.Diagnostics.Debug.WriteLine($"下载文件 {item}");
                HttpResponseMessage response = await client.GetAsync("https://blazor.app1.es/_content/DemoShared/samples/" + item);
                byte[] content = await response.Content.ReadAsByteArrayAsync();
                await File.WriteAllBytesAsync(Path.Combine(UploadPath, item), content);
                await File.WriteAllBytesAsync(Path.Combine(Path.GetTempPath(), item), content);
            }
        }

        await File.WriteAllTextAsync(Path.Combine(UploadPath, $"{DateTime.Now:yyMMdd_hhmmss}.txt"), DateTime.Now.ToString());
        System.Diagnostics.Debug.WriteLine($"写入文件txt完成");

        Status = "下载演示文件完成.";

    }

    void EmptyFiles()
    {
        Reset();

        Directory.GetFiles(UploadPath).ToList().ForEach(file =>File.Delete(file));

        Status = "已清空文件.";
    }

}